#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>

void *thread_function(void *arg);
sem_t bin_sem;

#define WORK_SIZE 1024
char work_area[WORK_SIZE];      /* 用来存放输入内容 */

int main() {
  int res;                    /* 暂存一些命令的返回结果 */
  pthread_t a_thread;         /* 织带新建的线程 */
  void *thread_result;       /* 存放线程处理结果 */

  res = sem_init(&bin_sem, 0, 0);   /* 初始化信号量，并且设置初始值为0*/
  if (res != 0) {
    perror("Semaphore initialization failed");
    exit(EXIT_FAILURE);
  }
  res = pthread_create(&a_thread, NULL, thread_function, NULL);   /* 创建新线程 */
  if (res != 0) {
    perror("Thread creation failed");
    exit(EXIT_FAILURE);
  }
  printf("Inout some text, Enter 'end' to finish\n");
  while(strncmp("end", work_area, 3) != 0) {             /* 当工作区内不是以end开头的字符串时...*/
    fgets(work_area, WORK_SIZE, stdin);                  /* 从标准输入获取输入到worl_area */
    sem_post(&bin_sem);                                  /* 信号量+1 */
  }
  printf("\nWaiting for thread to finish...\n");
  res = pthread_join(a_thread, &thread_result);         /* 等待线程结束 */
  if (res != 0) {
    perror("Thread join failed");
    exit(EXIT_FAILURE);
  }
  printf("Thread joined\n");
  sem_destroy(&bin_sem);                               /* 销毁信号量 */
  exit(EXIT_SUCCESS);
}

void *thread_function(void *arg) {
  sem_wait(&bin_sem);                                 /* 等待信号量有大于0的值然后-1 */
  while(strncmp("end", work_area, 3) != 0) {
    printf("You input %ld characters\n", strlen(work_area)-1);   /* 获取输入字符串长度 8*/
    sem_wait(&bin_sem);                               /* 等待信号量有大于0的值然后-1 */
  }
  pthread_exit(NULL);
}
